package com.hm.hall.commons.framework;


import com.hm.hall.commons.constans.jenum.LangEnum;
import com.hm.hall.commons.util.MyDbUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;


/**
 * @author Administrator
 */
public class PropertyPlaceholderConfigurerAppendCfgByDB extends PropertyPlaceholderConfigurer {
    public static Map<String, String> systemCfgProper = null;
    public static Map<String, String> langCfgProper = null;
    static Logger log = Logger.getLogger(PropertyPlaceholderConfigurerAppendCfgByDB.class);

    /**
     * 获得系统数据配置map对象
     *
     * @return
     */
    public static Map<String, String> getSystemCfgMap() {
        if (null == systemCfgProper) {
            systemCfgProper = new LinkedHashMap<>();
            String sql = "select ckey,cval from t_console_config where cgroup='system_cfg'";
            MyDbUtils.executeQuery(sql, new MyDbUtils.ExecuteQuery() {
                @Override
                public Object executeQuery(ResultSet rs) throws SQLException, UnsupportedEncodingException {
                    while (rs.next()) {
                        systemCfgProper.put(rs.getString("ckey"), new String(rs.getString("cval").getBytes("ISO-8859-1"), "UTF-8"));
                    }
                    return null;
                }
            });
        }
        if (systemCfgProper.isEmpty()) {
            systemCfgProper = null;
        }
        return systemCfgProper;
    }

    /**
     * 获得系统数据配置 value
     *
     * @param key
     * @return
     */
    public static String getDbSysCfgProper(String key) {
        if (null == systemCfgProper) {
            systemCfgProper = getSystemCfgMap();
        }
        return systemCfgProper.get(key);
    }

    /**
     * 获得多语言配置map对象
     *
     * @return
     */
    public static Map<String, String> getLangCfgMap() {
        if (null == langCfgProper) {
            langCfgProper = new LinkedHashMap<>();
            for (LangEnum langEnum : LangEnum.values()) {
                String lang = langEnum.lang;
                Properties prop = new Properties();
                // 装载配置文件
                try {
                    prop.load(PropertyPlaceholderConfigurerAppendCfgByDB.class.getResourceAsStream("/mess_" + lang + ".properties"));
                    //prop.load(new FileInputStream(new File("src\\main\\resources\\mess_" + lang + ".properties")));
                    Enumeration en = prop.propertyNames();
                    while (en.hasMoreElements()) {
                        String key = (String) en.nextElement();
                        String value = prop.getProperty(key);
                        langCfgProper.put(lang + "_" + key, value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (langCfgProper.isEmpty()) {
            langCfgProper = null;
        }
        return langCfgProper;
    }

    /**
     * 获得多语言配置 value
     *
     * @param key
     * @return
     */
    public static String getLangCfgProper(String key) {
        if (null == langCfgProper) {
            langCfgProper = getLangCfgMap();
        }
        return langCfgProper.get(key);
    }

    @Override
    public void setLocations(Resource... locations) {
        try {
            for (int i = 0; i < locations.length; i++) {
                Resource location = locations[i];
                // 是否是系统配置文件,是系统配置文件就重写,追加数据库配置信息
                if (location.getFilename().contains("configs-")) {
                    ClassPathResource classPathResource = ((ClassPathResource) location);
                    classPathResource = new MyClassPathResourceAppendCfgByDB(classPathResource.getPath());
                    locations[i] = classPathResource;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.setLocations(locations);
    }

    /**
     * 加入一些数据库中的配置信息
     */
    public static class MyClassPathResourceAppendCfgByDB extends ClassPathResource {
        public String path2;

        public MyClassPathResourceAppendCfgByDB(String path) {
            super(path);
            path2 = path;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            InputStream is = ClassUtils.getDefaultClassLoader().getResourceAsStream(path2);
            String cfgContent = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
            is.close();

            cfgContent += fetchSysCfgPropertyByDb();
            is = new ByteArrayInputStream(cfgContent.getBytes());
            return is;
        }

        /**
         * 从数据中获得系统property 文件配置内容
         */
        public String fetchSysCfgPropertyByDb() {
            Map<String, String> systemCfgMap = getSystemCfgMap();
            String sysCfgProperty = "";
            for (Map.Entry<String, String> entry : systemCfgMap.entrySet()) {
                sysCfgProperty += "\n" + entry.getKey() + "=" + entry.getValue();
            }
            return sysCfgProperty;
        }


    }

}
